﻿using Link_eLab.JwtAuthorizePolicy.Enum;
using Link_eLab.JwtAuthorizePolicy.Extension;
using Link_eLab.SqlSugar.Extension;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using Configuration.ServerApi.Constant;
using Configuration.ServerApi.Dao;
using Configuration.ServerApi.Entity;
using Configuration.ServerApi.Param;
using SqlSugar;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using static OpcUaHelper.CryptHelper;

namespace Configuration.ServerApi.Service.Impl
{
    /// <summary>
    /// UserService
    /// </summary>
    public class UserService : IUserService
    {
        private readonly IConfiguration Configuration;
        private readonly IHttpContextAccessor Accessor;
        private readonly ISysUserDao SysUserDao;
        private readonly ISysRoleDao SysRoleDao;
        private readonly IBisOperationRecordDao BisOperationRecordDao;

        #region 构造函数

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="accessor"></param>
        /// <param name="sysUserDao"></param>
        /// <param name="sysRoleDao"></param>
        /// <param name="bisOperationRecordDao"></param>
        public UserService(IConfiguration configuration,
            IHttpContextAccessor accessor,
            ISysUserDao sysUserDao,
            ISysRoleDao sysRoleDao,
            IBisOperationRecordDao bisOperationRecordDao)
        {
            Configuration = configuration;
            Accessor = accessor;
            SysUserDao = sysUserDao;
            SysRoleDao = sysRoleDao;
            BisOperationRecordDao = bisOperationRecordDao;
        }

        #endregion 构造函数

        #region 公用方法

        #region 姓名加密变星 (*)

        /// <summary>
        /// 姓名加密变星 (*)
        /// 
        /// 姓名长度为2位时：第二位变星 (示例: 张三 => 张*)
        /// 姓名长度为3位时：第二位变星 (示例: 王老五 => 王*五)
        /// 姓名长度大于3位时：第一位与最后一位不变星，其余均变星 (示例：唐吉坷德 => 唐**德)
        /// </summary>
        /// <param name="name">姓名</param>
        /// <returns>加密后姓名</returns>
        public static string NameEncryption(string name)
        {
            // 姓名为空时直接返回字符串
            if (string.IsNullOrEmpty(name))
            {
                return "";
            }

            // 将字符串分割为字符数组
            char[] tempChar = name.ToCharArray();

            // 处理字符
            if (tempChar.Length == 2)
            {
                // 第二个字符变为*
                tempChar[1] = '*';
            }
            else if (tempChar.Length == 3)
            {
                // 第二个字符变为*
                tempChar[1] = '*';
            }
            else
            {
                // 第一个字符与最后一个字符不变为*
                for (int i = 1; i < tempChar.Length - 2; i++)
                {
                    tempChar[i] = '*';
                }
            }

            // 设置返回结果
            string result = string.Join("", tempChar);
            Console.WriteLine($"result：{result}");

            return result;
        }

        #endregion

        #endregion

        #region 用户登录

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="param">更新参数集</param>
        /// <returns>JSON结果集</returns>
        public async Task<JsonResult> AuthLogin(UpdateModel param)
        {
            Console.WriteLine("\n用户登录：AuthLogin");

            #region 参数校验

            Console.WriteLine($"phone：{param.Phone}");
            Console.WriteLine($"password：{param.PassWord}");

            if (string.IsNullOrEmpty(param.Phone) || string.IsNullOrEmpty(param.PassWord))
            {
                return new JsonResult(new ResultModel
                {
                    Code = -1,
                    Msg = "参数错误"
                });
            }

            #endregion

            #region 初始化参数

            object token = new object();                                      // 用户授权Token
            string msg = "登录成功";                                            // 返回信息

            #endregion

            #region 验证登录用户身份信息

            Console.WriteLine("\n验证登录用户身份信息");

            sys_user user = await SysUserDao.QuerySingle(w => w.Del_Flag == 0 && w.Phone.Equals(param.Phone));
            if (user == null)
            {
                Console.WriteLine("\n未获取到当前账号的账户信息，停止执行。");
                return new JsonResult(new ResultModel
                {
                    Success = false,
                    Msg = "当前账号未在系统注册，请先注册"
                });
            }

            AESCrypt aesCrypt = new AESCrypt();
            if (!param.PassWord.Equals(aesCrypt.Decrypt(user.PassWord)))
            {
                Console.WriteLine("\n当前账号登录密码输入错误，停止执行。");
                return new JsonResult(new ResultModel
                {
                    Success = false,
                    Msg = "账号或密码错误，请重新登录"
                });
            }

            #endregion

            #region 生成登录用户Token信息

            Console.WriteLine("\n生成登录用户Token信息");

            // 如果是基于用户的授权策略，这里要添加用户;如果是基于角色的授权策略，这里要添加角色
            Claim[] claims_company = new Claim[]
            {
                new Claim("userId", user.Id.ToString()),
                new Claim("userName", user.Name ?? string.Empty),
                new Claim("userRoleId", user.RoleId ?? string.Empty),
                new Claim("userRoleName", user.RoleName ?? string.Empty),
                new Claim("userPhone", user.Phone ?? string.Empty),
                new Claim("orgId", user.OrgGuid ?? string.Empty),
                new Claim("orgName", user.OrgName ?? string.Empty),
                new Claim("clientType", "Robot"),
                new Claim("jti", Guid.NewGuid().ToString().ToUpper())
            };

            // 用户标识
            ClaimsIdentity identity_company = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);
            identity_company.AddClaims(claims_company);

            PermissionRequirement requirement = new PermissionRequirement(
                Configuration["Audience:Issuer"].ToString(),
                Configuration["Audience:Audience"].ToString(),
                new SigningCredentials(
                    new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Audience:Secret"].ToString())),
                    SecurityAlgorithms.HmacSha256),
                Configuration["Audience:OpenJwt"].ToString());

            // 设置用户Token信息
            token = JwtToken.BuildJwtToken(claims_company, requirement, AuthClientType.SaasPlatForm);

            #endregion

            #region 新增操作记录

            int AddRecord = await BisOperationRecordDao.Insert(new bis_operation_record()
            {
                Id = Guid.NewGuid().ToString().ToUpper(),
                Content = $"{user.Name} 登录了系统",
                OrgGuid = user.OrgGuid,
                OrgName = user.OrgName,
                CreateUser = user.Id,
                CreateUserName = user.Name,
                CreateTime = DateTime.Now,
                UpdateUser = user.Id,
                UpdateUserName = user.Name,
                UpdateTime = DateTime.Now,
                Del_Flag = 0
            });

            #endregion

            Console.WriteLine("\n登录授权验证通过，返回结果信息");
            return new JsonResult(new
            {
                Code = 0,
                Success = true,
                Msg = msg,
                Data = user,
                Token = token
            });
        }

        #endregion

        #region 修改登录用户密码

        /// <summary>
        /// 修改登录用户密码
        /// </summary>
        /// <param name="param">更新参数集</param>
        /// <returns>JSON结果集</returns>
        public async Task<JsonResult> UpdateLoginUserPassword(UpdateModel param)
        {
            Console.WriteLine("\n修改密码：UpdateLoginUserPassword");

            #region 参数、数据校验

            Console.WriteLine($"OldPassword：{param.OldPassword}");
            Console.WriteLine($"NewPassword：{param.NewPassword}");

            if (string.IsNullOrEmpty(param.OldPassword) ||
                string.IsNullOrEmpty(param.NewPassword))
            {
                return new JsonResult(new
                {
                    Code = 0,
                    Success = false,
                    Msg = "必填参数不能为空"
                });
            }

            #endregion 

            #region 获取所需数据

            string userId = Accessor.HttpContext.User.Claims.First(i => i.Type == "userId").Value;
            string userName = Accessor.HttpContext.User.Claims.First(i => i.Type == "userName").Value;

            #endregion

            #region 数据提交

            // 获取登录用户详情
            var userData = await SysUserDao.QuerySingle(w => w.Del_Flag == 0 && w.Id.Equals(userId));
            if (userData == null)
            {
                return new JsonResult(new ResultModel
                {
                    Success = false,
                    Msg = "登录用户信息异常, 请联系管理员"
                });
            }

            AESCrypt aesCrypt = new AESCrypt();
            if (!param.OldPassword.Equals(aesCrypt.Decrypt(userData.PassWord)))
            {
                return new JsonResult(new ResultModel
                {
                    Success = false,
                    Msg = "输入的旧密码不正确, 请检查后重试"
                });
            }

            if (param.NewPassword.Trim().Length < 6)
            {
                return new JsonResult(new ResultModel
                {
                    Success = false,
                    Msg = "新密码长度过短, 请重试"
                });
            }

            var result = SysUserDao.Update(u => new sys_user()
            {
                PassWord = aesCrypt.Encrypt(param.NewPassword)
            }, w => w.Id.Equals(userId));

            return new JsonResult(new ResultModel
            {
                Msg = "密码修改成功"
            });

            #endregion
        }

        #endregion

        #region 获取用户列表

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="param">搜索条件</param>
        /// <returns>JSON结果集</returns>
        public async Task<JsonResult> UserList(SearchModel param)
        {
            Console.WriteLine("\n获取用户列表：UserList");

            #region 获取登录用户相关信息

            string orgId = string.Empty;
            string userId = string.Empty;
            string userRoleId = string.Empty;
            try
            {
                orgId = Accessor.HttpContext.User.Claims.First(i => i.Type == "orgId").Value;
                userId = Accessor.HttpContext.User.Claims.First(i => i.Type == "userId").Value;
                userRoleId = Accessor.HttpContext.User.Claims.First(i => i.Type == "userRoleId").Value;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return new JsonResult(new ResultModel
                {
                    Success = false,
                    Msg = "Token已过期, 请重新登录"
                });
            }

            #endregion

            // 初始化数据查询表达式
            Expression<Func<sys_user, bool>> expression = w => w.Del_Flag == 0;

            Console.WriteLine($"Name：{param.Name}");
            if (!string.IsNullOrEmpty(param.Name))
            {
                expression = expression.And(w => w.Name.Contains(param.Name));
            }

            Console.WriteLine($"Phone：{param.Phone}");
            if (!string.IsNullOrEmpty(param.Phone))
            {
                expression = expression.And(w => w.Phone.Contains(param.Phone));
            }

            Console.WriteLine($"RoleId：{param.RoleId}");
            if (!string.IsNullOrEmpty(param.RoleId))
            {
                expression = expression.And(w => w.RoleId.Contains(param.RoleId));
            }

            Console.WriteLine($"RoleName：{param.RoleName}");
            if (!string.IsNullOrEmpty(param.RoleName))
            {
                expression = expression.And(w => w.RoleName.Contains(param.RoleName));
            }

            Console.WriteLine($"Status：{param.Status}");
            if (!string.IsNullOrEmpty(param.Status))
            {
                expression = expression.And(w => w.Status.Equals(param.Status));
            }

            Console.WriteLine($"OrgGuid：{param.OrgGuid}");
            if (!string.IsNullOrEmpty(param.OrgGuid))
            {
                expression = expression.And(w => w.OrgGuid.Equals(param.OrgGuid));
            }

            Console.WriteLine($"OrgName：{param.OrgName}");
            if (!string.IsNullOrEmpty(param.OrgName))
            {
                expression = expression.And(w => w.OrgName.Equals(param.OrgName));
            }

            dynamic result = null;
            if (param.Page != null && param.Limit != null)
            {
                result = await SysUserDao.QueryByWherePage(param.Page.Value, param.Limit.Value, expression, o => o.CreateTime, OrderByType.Desc);
            }
            else
            {
                result = await SysUserDao.QueryByWhere(expression, o => o.CreateTime, OrderByType.Desc);
            }
            var count = await SysUserDao.QueryCount(expression);

            return new JsonResult(new ResultModel
            {
                Count = count,
                Data = result
            });
        }

        #endregion

        #region 获取用户详情

        /// <summary>
        /// 获取用户详情
        /// </summary>
        /// <param name="param">搜索条件</param>
        /// <returns>JSON结果集</returns>
        public async Task<JsonResult> UserDetail(SearchModel param)
        {
            Console.WriteLine("\n获取用户详情：UserDetail");

            #region 参数校验

            Console.WriteLine($"Id：{param.Id}");
            if (string.IsNullOrEmpty(param.Id))
            {
                return new JsonResult(new ResultModel
                {
                    Success = false,
                    Msg = "必填参数不能为空"
                });
            }

            #endregion

            return new JsonResult(new ResultModel
            {
                Data = await SysUserDao.QuerySingle(w => w.Del_Flag == 0 && w.Id.Equals(param.Id))
            });
        }

        #endregion

        #region 获取登录用户详情

        /// <summary>
        /// 获取登录用户详情
        /// </summary>
        /// <returns>JSON结果集</returns>
        public async Task<JsonResult> LoginUserDetail()
        {
            Console.WriteLine("\n获取登录用户详情：LoginUserDetail");

            #region 获取登录用户相关信息

            string userId = string.Empty;
            try
            {
                userId = Accessor.HttpContext.User.Claims.First(i => i.Type == "userId").Value;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return new JsonResult(new ResultModel
                {
                    Success = false,
                    Msg = "Token已过期, 请重新登录"
                });
            }

            #endregion

            return new JsonResult(new ResultModel
            {
                Data = await SysUserDao.QuerySingle(w => w.Del_Flag == 0 && w.Id.Equals(userId))
            });
        }

        #endregion

        #region 提交用户信息

        /// <summary>
        /// 提交用户信息
        /// </summary>
        /// <param name="param">更新参数集</param>
        /// <returns>JSON结果集</returns>
        public async Task<JsonResult> SubmitUser(UpdateModel param)
        {
            Console.WriteLine("\n提交用户信息：SubmitUser");

            #region 参数、数据校验

            Console.WriteLine($"Id：{param.UserData.Id}");

            if (string.IsNullOrEmpty(param.UserData.Name) ||
                string.IsNullOrEmpty(param.UserData.Phone))
            {
                return new JsonResult(new ResultModel
                {
                    Success = false,
                    Msg = "必填参数不能为空"
                });
            }

            #endregion 

            #region 获取所需数据

            #region 获取登录用户相关信息

            string userId = string.Empty;
            string userName = string.Empty;
            string orgId = string.Empty;
            string orgName = string.Empty;
            try
            {
                userId = Accessor.HttpContext.User.Claims.First(i => i.Type == "userId").Value;
                userName = Accessor.HttpContext.User.Claims.First(i => i.Type == "userName").Value;
                orgId = Accessor.HttpContext.User.Claims.First(i => i.Type == "orgId").Value;
                orgName = Accessor.HttpContext.User.Claims.First(i => i.Type == "orgName").Value;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return new JsonResult(new ResultModel
                {
                    Success = false,
                    Msg = "Token已过期, 请重新登录"
                });
            }

            #endregion

            #endregion

            #region 数据提交

            DateTime now = DateTime.Now;
            Guid guid = Guid.NewGuid();
            string newId = guid.ToString().ToUpper();

            int result = 0;

            string tempOrgGuid = !string.IsNullOrEmpty(param.UserData.OrgGuid) ? param.UserData.OrgGuid : orgId;
            string tempOrgName = !string.IsNullOrEmpty(param.UserData.OrgName) ? param.UserData.OrgName : orgName;

            // 如果Guid为空时则新增，否则为编辑
            if (string.IsNullOrEmpty(param.UserData.Id))
            {
                #region 前置数据验证

                // 校验账号
                var checkResult_accountNumber = SysUserDao.QueryCount(w => w.Del_Flag == 0 && w.AccountNumber.Equals(param.UserData.AccountNumber)).Result;
                if (checkResult_accountNumber > 0)
                {
                    return new JsonResult(new ResultModel
                    {
                        Success = false,
                        Msg = "此账号已存在, 请修改后重试"
                    });
                }

                // 校验手机号
                var checkResult_phone = SysUserDao.QueryCount(w => w.Del_Flag == 0 && w.Phone.Equals(param.UserData.Phone)).Result;
                if (checkResult_phone > 0)
                {
                    return new JsonResult(new ResultModel
                    {
                        Success = false,
                        Msg = "此手机号已存在, 请修改后重试"
                    });
                }

                #endregion

                AESCrypt aesCrypt = new AESCrypt();
                var model = new sys_user()
                {
                    Id = newId,
                    Name = param.UserData.Name,
                    Sex = param.UserData.Sex,
                    RoleId = param.UserData.RoleId,
                    RoleName = param.UserData.RoleName,
                    JobNumber = param.UserData.JobNumber,
                    AccountNumber = param.UserData.AccountNumber,
                    PassWord = aesCrypt.Encrypt(CommonConstant.USER_DEFAULT_PASSWORD),
                    Phone = param.UserData.Phone,
                    Email = param.UserData.Email,
                    Status = param.UserData.Status,
                    Remark = param.UserData.Remark,
                    OrgGuid = tempOrgGuid,
                    OrgName = tempOrgName,
                    CreateUser = userId,
                    CreateUserName = userName,
                    CreateTime = now,
                    UpdateUser = userId,
                    UpdateUserName = userName,
                    UpdateTime = now,
                    Del_Flag = 0
                };
                result = await SysUserDao.Insert(model);

                return new JsonResult(new ResultModel
                {
                    Msg = "新增成功"
                });
            }
            else
            {
                #region 前置数据验证

                // 校验账号
                var checkResult_accountNumber = SysUserDao.QueryByWhere(w => w.Del_Flag == 0 && w.AccountNumber.Equals(param.UserData.AccountNumber), null).Result;
                if (checkResult_accountNumber.Count + 1 > 2 || (checkResult_accountNumber.Count == 1 && !checkResult_accountNumber.FirstOrDefault().Id.Equals(param.UserData.Id)))
                {
                    return new JsonResult(new ResultModel
                    {
                        Success = false,
                        Msg = "此账号已存在, 请修改后重试"
                    });
                }

                // 校验手机号
                var checkResult_phone = SysUserDao.QueryByWhere(w => w.Del_Flag == 0 && w.Phone.Equals(param.UserData.Phone), null).Result;
                if (checkResult_phone.Count + 1 > 2 || (checkResult_phone.Count == 1 && !checkResult_phone.FirstOrDefault().Id.Equals(param.UserData.Id)))
                {
                    return new JsonResult(new ResultModel
                    {
                        Success = false,
                        Msg = "此手机号已存在, 请修改后重试"
                    });
                }

                #endregion

                result = SysUserDao.Update(u => new sys_user()
                {
                    Name = param.UserData.Name,
                    Sex = param.UserData.Sex,
                    RoleId = param.UserData.RoleId,
                    RoleName = param.UserData.RoleName,
                    JobNumber = param.UserData.JobNumber,
                    AccountNumber = param.UserData.AccountNumber,
                    Phone = param.UserData.Phone,
                    Email = param.UserData.Email,
                    Status = param.UserData.Status,
                    Remark = param.UserData.Remark,
                    OrgGuid = tempOrgGuid,
                    OrgName = tempOrgName,
                    UpdateUser = userId,
                    UpdateUserName = userName,
                    UpdateTime = now,
                }, w => w.Id.Equals(param.UserData.Id)).Result;

                return new JsonResult(new ResultModel
                {
                    Msg = "编辑成功"
                });
            }

            #endregion 数据提交
        }

        #endregion

        #region 批量启用或禁用用户

        /// <summary>
        /// 批量启用或禁用用户
        /// </summary>
        /// <param name="param">更新参数集</param>
        /// <returns>JSON结果集</returns>
        public async Task<JsonResult> UpdateUserStatus(UpdateModel param)
        {
            Console.WriteLine("\n批量启用或禁用用户：UpdateUserStatus");

            #region 参数效验

            Console.WriteLine($"Id：{param.Id}");
            Console.WriteLine($"Status：{param.Status}");

            if (string.IsNullOrEmpty(param.Id) ||
                string.IsNullOrEmpty(param.Status))
            {
                return new JsonResult(new ResultModel
                {
                    Success = false,
                    Msg = "必填参数不能为空"
                });
            }

            #endregion

            #region 获取登录用户相关信息

            string userId = string.Empty;
            string userName = string.Empty;
            try
            {
                userId = Accessor.HttpContext.User.Claims.First(i => i.Type == "userId").Value;
                userName = Accessor.HttpContext.User.Claims.First(i => i.Type == "userName").Value;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return new JsonResult(new ResultModel
                {
                    Success = false,
                    Msg = "Token已过期, 请重新登录"
                });
            }

            #endregion

            string[] idArray = param.Id.Split(',');

            int result = 0;
            foreach (var item in idArray)
            {
                Console.WriteLine(item);
                if (!item.Equals(userId))
                {
                    result += await SysUserDao.Update(u => new sys_user
                    {
                        Status = param.Status,
                        UpdateUser = userId,
                        UpdateUserName = userName,
                        UpdateTime = DateTime.Now
                    }, w => w.Id.Equals(item));
                }
            }

            return new JsonResult(new ResultModel
            {
                Msg = "更新成功",
                Data = result
            });
        }

        #endregion

        #region 批量删除用户信息

        /// <summary>
        /// 批量删除用户信息
        /// </summary>
        /// <param name="param">更新参数集</param>
        /// <returns>JSON结果集</returns>
        public async Task<JsonResult> DelUser(UpdateModel param)
        {
            Console.WriteLine("\n批量删除用户信息：DelUser");

            #region 参数效验

            Console.WriteLine($"Id：{param.Id}");

            if (string.IsNullOrEmpty(param.Id))
            {
                return new JsonResult(new ResultModel
                {
                    Success = false,
                    Msg = "必填参数不能为空"
                });
            }

            #endregion

            #region 获取登录用户相关信息

            string userId = string.Empty;
            string userName = string.Empty;
            try
            {
                userId = Accessor.HttpContext.User.Claims.First(i => i.Type == "userId").Value;
                userName = Accessor.HttpContext.User.Claims.First(i => i.Type == "userName").Value;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return new JsonResult(new ResultModel
                {
                    Success = false,
                    Msg = "Token已过期, 请重新登录"
                });
            }

            #endregion

            string[] idArray = param.Id.Split(',');

            int result = 0;
            foreach (var item in idArray)
            {
                Console.WriteLine(item);
                if (!item.Equals(userId))
                {
                    result += await SysUserDao.Update(u => new sys_user
                    {
                        UpdateUser = userId,
                        UpdateUserName = userName,
                        UpdateTime = DateTime.Now,
                        Del_Flag = 1
                    }, w => w.Id.Equals(item));
                }
            }

            return new JsonResult(new ResultModel
            {
                Msg = "删除成功",
                Data = result
            });
        }

        #endregion

        #region 获取角色列表

        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <param name="param">搜索条件</param>
        /// <returns>JSON结果集</returns>
        public async Task<JsonResult> RoleList(SearchModel param)
        {
            Console.WriteLine("\n获取角色列表：RoleList");

            #region 获取登录用户相关信息

            string orgId = string.Empty;
            string userId = string.Empty;
            string userRoleId = string.Empty;
            try
            {
                orgId = Accessor.HttpContext.User.Claims.First(i => i.Type == "orgId").Value;
                userId = Accessor.HttpContext.User.Claims.First(i => i.Type == "userId").Value;
                userRoleId = Accessor.HttpContext.User.Claims.First(i => i.Type == "userRoleId").Value;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return new JsonResult(new ResultModel
                {
                    Success = false,
                    Msg = "Token已过期, 请重新登录"
                });
            }

            #endregion

            // 初始化数据查询表达式
            Expression<Func<sys_role, bool>> expression = w => w.Del_Flag == 0;

            Console.WriteLine($"Name：{param.Name}");
            if (!string.IsNullOrEmpty(param.Name))
            {
                expression = expression.And(w => w.Name.Contains(param.Name));
            }

            Console.WriteLine($"Status：{param.Status}");
            if (!string.IsNullOrEmpty(param.Status))
            {
                expression = expression.And(w => w.Status.Equals(param.Status));
            }

            dynamic result = null;
            if (param.Page != null && param.Limit != null)
            {
                result = await SysRoleDao.QueryByWherePage(param.Page.Value, param.Limit.Value, expression, o => o.CreateTime, OrderByType.Desc);
            }
            else
            {
                result = await SysRoleDao.QueryByWhere(expression, o => o.CreateTime, OrderByType.Desc);
            }
            var count = await SysRoleDao.QueryCount(expression);

            return new JsonResult(new ResultModel
            {
                Count = count,
                Data = result
            });
        }

        #endregion

        #region 获取角色详情

        /// <summary>
        /// 获取角色详情
        /// </summary>
        /// <param name="param">搜索条件</param>
        /// <returns>JSON结果集</returns>
        public async Task<JsonResult> RoleDetail(SearchModel param)
        {
            Console.WriteLine("\n获取角色详情：RoleDetail");

            #region 参数校验

            Console.WriteLine($"Id：{param.Id}");
            if (string.IsNullOrEmpty(param.Id))
            {
                return new JsonResult(new ResultModel
                {
                    Success = false,
                    Msg = "必填参数不能为空"
                });
            }

            #endregion

            return new JsonResult(new ResultModel
            {
                Data = await SysRoleDao.QuerySingle(w => w.Del_Flag == 0 && w.Id.Equals(param.Id))
            });
        }

        #endregion

        #region 提交角色信息

        /// <summary>
        /// 提交角色信息
        /// </summary>
        /// <param name="param">更新参数集</param>
        /// <returns>JSON结果集</returns>
        public async Task<JsonResult> SubmitRole(UpdateModel param)
        {
            Console.WriteLine("\n提交角色信息：SubmitRole");

            #region 参数、数据校验

            Console.WriteLine($"Id：{param.RoleData.Id}");

            if (string.IsNullOrEmpty(param.RoleData.Name))
            {
                return new JsonResult(new ResultModel
                {
                    Success = false,
                    Msg = "必填参数不能为空"
                });
            }

            #endregion 

            #region 获取所需数据

            #region 获取登录用户相关信息

            string userId = string.Empty;
            string userName = string.Empty;
            string orgId = string.Empty;
            string orgName = string.Empty;
            try
            {
                userId = Accessor.HttpContext.User.Claims.First(i => i.Type == "userId").Value;
                userName = Accessor.HttpContext.User.Claims.First(i => i.Type == "userName").Value;
                orgId = Accessor.HttpContext.User.Claims.First(i => i.Type == "orgId").Value;
                orgName = Accessor.HttpContext.User.Claims.First(i => i.Type == "orgName").Value;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return new JsonResult(new ResultModel
                {
                    Success = false,
                    Msg = "Token已过期, 请重新登录"
                });
            }

            #endregion

            #endregion

            #region 数据提交

            DateTime now = DateTime.Now;
            Guid guid = Guid.NewGuid();
            string newId = guid.ToString().ToUpper();

            int result = 0;

            // 如果Guid为空时则新增，否则为编辑
            if (param.RoleData.Id == null)
            {
                #region 前置数据验证

                // 校验角色名称
                var checkResult_name = SysRoleDao.QueryCount(w => w.Del_Flag == 0 && w.Name.Equals(param.RoleData.Name)).Result;
                if (checkResult_name > 0)
                {
                    return new JsonResult(new ResultModel
                    {
                        Success = false,
                        Msg = "此角色名称已存在, 请修改后重试"
                    });
                }

                #endregion

                var model = new sys_role()
                {
                    Name = param.RoleData.Name,
                    Status = param.RoleData.Status,
                    IsDefault = param.RoleData.IsDefault,
                    Remark = param.RoleData.Remark,
                    OrgGuid = orgId,
                    OrgName = orgName,
                    CreateUser = userId,
                    CreateUserName = userName,
                    CreateTime = now,
                    UpdateUser = userId,
                    UpdateUserName = userName,
                    UpdateTime = now,
                    Del_Flag = 0
                };
                result = await SysRoleDao.Insert(model);

                return new JsonResult(new ResultModel
                {
                    Msg = "新增成功"
                });
            }
            else
            {
                #region 前置数据验证

                // 校验角色名称
                var checkResult_name = SysRoleDao.QueryByWhere(w => w.Del_Flag == 0 && w.Name.Equals(param.RoleData.Name), null).Result;
                if (checkResult_name.Count + 1 > 2 || (checkResult_name.Count == 1 && checkResult_name.FirstOrDefault().Id != param.RoleData.Id))
                {
                    return new JsonResult(new ResultModel
                    {
                        Success = false,
                        Msg = "此角色名称已存在, 请修改后重试"
                    });
                }

                #endregion

                result = SysRoleDao.Update(u => new sys_role()
                {
                    Name = param.RoleData.Name,
                    Status = param.RoleData.Status,
                    IsDefault = param.RoleData.IsDefault,
                    Remark = param.RoleData.Remark,
                    UpdateUser = userId,
                    UpdateUserName = userName,
                    UpdateTime = now,
                }, w => w.Id.Equals(param.RoleData.Id)).Result;

                return new JsonResult(new ResultModel
                {
                    Msg = "编辑成功"
                });
            }

            #endregion 数据提交
        }

        #endregion

        #region 批量启用或禁用角色

        /// <summary>
        /// 批量启用或禁用角色
        /// </summary>
        /// <param name="param">更新参数集</param>
        /// <returns>JSON结果集</returns>
        public async Task<JsonResult> UpdateRoleStatus(UpdateModel param)
        {
            Console.WriteLine("\n批量启用或禁用角色：UpdateRoleStatus");

            #region 参数效验

            Console.WriteLine($"Id：{param.Id}");
            Console.WriteLine($"Status：{param.Status}");

            if (string.IsNullOrEmpty(param.Id) ||
                string.IsNullOrEmpty(param.Status))
            {
                return new JsonResult(new ResultModel
                {
                    Success = false,
                    Msg = "必填参数不能为空"
                });
            }

            #endregion

            #region 获取登录用户相关信息

            string userId = string.Empty;
            string userName = string.Empty;
            try
            {
                userId = Accessor.HttpContext.User.Claims.First(i => i.Type == "userId").Value;
                userName = Accessor.HttpContext.User.Claims.First(i => i.Type == "userName").Value;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return new JsonResult(new ResultModel
                {
                    Success = false,
                    Msg = "Token已过期, 请重新登录"
                });
            }

            #endregion

            string[] idArray = param.Id.Split(',');

            int result = 0;
            foreach (var item in idArray)
            {
                Console.WriteLine(item);
                if (!item.Equals(userId))
                {
                    result += await SysRoleDao.Update(u => new sys_role
                    {
                        Status = param.Status,
                        UpdateUser = userId,
                        UpdateUserName = userName,
                        UpdateTime = DateTime.Now
                    }, w => w.Id.Equals(item));
                }
            }

            return new JsonResult(new ResultModel
            {
                Msg = "更新成功",
                Data = result
            });
        }

        #endregion

        #region 批量删除角色信息

        /// <summary>
        /// 批量删除角色信息
        /// </summary>
        /// <param name="param">更新参数集</param>
        /// <returns>JSON结果集</returns>
        public async Task<JsonResult> DelRole(UpdateModel param)
        {
            Console.WriteLine("\n批量删除角色信息：DelRole");

            #region 参数效验

            Console.WriteLine($"Id：{param.Id}");

            if (string.IsNullOrEmpty(param.Id))
            {
                return new JsonResult(new ResultModel
                {
                    Success = false,
                    Msg = "必填参数不能为空"
                });
            }

            #endregion

            #region 获取登录用户相关信息

            string userId = string.Empty;
            string userName = string.Empty;
            try
            {
                userId = Accessor.HttpContext.User.Claims.First(i => i.Type == "userId").Value;
                userName = Accessor.HttpContext.User.Claims.First(i => i.Type == "userName").Value;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return new JsonResult(new ResultModel
                {
                    Success = false,
                    Msg = "Token已过期, 请重新登录"
                });
            }

            #endregion

            string[] idArray = param.Id.Split(',');

            int result = 0;
            foreach (var item in idArray)
            {
                Console.WriteLine(item);
                if (!item.Equals(userId))
                {
                    result += await SysRoleDao.Update(u => new sys_role
                    {
                        UpdateUser = userId,
                        UpdateUserName = userName,
                        UpdateTime = DateTime.Now,
                        Del_Flag = 1
                    }, w => w.Id.Equals(item));
                }
            }

            return new JsonResult(new ResultModel
            {
                Msg = "删除成功",
                Data = result
            });
        }

        #endregion

    }
}